package com.myhome.mail.config;

import com.myhome.entity.Employee;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component
public class mailConfig {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;



    @RabbitListener(queues = "mail")
    public void setMail(Employee employee){
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg);
        try {
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setTo(employee.getEmail());
            mimeMessageHelper.setSubject("入职欢迎邮件");
            mimeMessageHelper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.getName());
            String mail = templateEngine.process("mail", context);
            mimeMessageHelper.setText(mail,true);

            //mimeMessageHelper.addAttachment("q",new ByteArrayResource(new byte[1]));

            javaMailSender.send(msg);
        } catch (Exception e) {
            System.out.println("发送失败"+e.getMessage());
        }
    }
}
